package com.tensquare.user.controller;

import com.tensquare.user.pojo.Admin;
import com.tensquare.user.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import utils.IdWorker;
import utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Handler;

/**
 * Created by WF on 2020/7/27 14:43
 */
@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;
    //1.添加管理员
    @PostMapping
    public Result add(@RequestBody Admin admin){
        //1.1)添加管理员用户
        adminService.add(admin);
        //1.2)返回
        return new Result(true, StatusCode.OK,"添加管理员成功！");
    }
    //2.管理员登录
    @PostMapping("login")
    public Result login(@RequestBody Admin admin){
        //2.1)根据用户名及密码进行登录查询
        Admin loginAdmin = adminService.login(admin.getLoginname(),admin.getPassword());
        //2.2)将管理员信息放到token中
        String token = jwtUtil.createJWT(loginAdmin.getId(), loginAdmin.getLoginname(), "admin");
        Map map = new HashMap<>();
        map.put("name",loginAdmin.getLoginname());
        map.put("token",token);
        //2.2)返回
        if(loginAdmin != null){
            return new Result(true,StatusCode.OK,"管理员登录成功！",map);
        }
        return new Result(false,StatusCode.LOGINERROR,"管理员登录失败！",map);
    }
    //3.删除用户
    @DeleteMapping("{adminId}")
    public Result delete(@PathVariable String adminId){
        //3.1)从请求作用域中得到claims
        Claims claims = (Claims) request.getAttribute("claims");
        //3.2)判断是否存在
        if(claims != null){
            //3.3)得到角色的值
            String roles = (String) claims.get("roles");
            //3.4)判断是否存在
            if(!StringUtils.isEmpty(roles) && "admin".equals(roles)){
                adminService.delete(adminId);
                return new Result(true,StatusCode.OK,"删除管理员成功！");
            }
        }
        return new Result(false,StatusCode.ACCESSERROR,"无管理员访问权限！");
    }
}
